package com.huanzhidadi.single.produceconsumer;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * 对比CountdownLatchTest
 */
@Slf4j
public class SynchronousQueueTest {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        SynchronousQueue<Object> synchronousQueue = new SynchronousQueue<>();

        Runnable producer = () -> {
            while (true) {
                log.info("生产者开始生产，请等待。。。");
                try {
                    Thread.sleep(2000l);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Object object = new Object();
                log.info("产品生产完成。");
                log.info("produced {}", object);
                try {
                    synchronousQueue.put(object);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        Runnable consumer = () -> {
            try {
                while (true) {
                    log.info("消费者等待中。。。");
                    Object object = synchronousQueue.take();
                    log.info("消费者得到产品");
                    log.info("consumed {}", object);
                }
            } catch (InterruptedException ex) {
                log.error(ex.getMessage(),ex);
            }
        };

        executor.submit(producer);
        executor.submit(consumer);

        executor.awaitTermination(5000, TimeUnit.MILLISECONDS);
        executor.shutdown();

    }
}
